﻿using System;
using Atmk.WaterMeter.EF;
using Atmk.WaterMeter.MIS.Base;
using Atmk.WaterMeter.MIS.Common;
using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.Statistics;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Atmk.WaterMeter.MIS.Controllers
{
    /// <summary>
    /// 合并查询类
    /// </summary>
    [Authorize]
    public class MergeQueryController: BaseApiController
    {
        private static ILogger<MergeQueryController> _logger;
        private readonly TokenHelper _tokenHelper;
        private readonly IBaseInfoLogic _baseStatistcsLogic;
        private readonly IQueryDatasLogic _queryDatasLogic;

        /// <inheritdoc />
        public MergeQueryController(
            ILogger<MergeQueryController> logger,
            IBaseInfoLogic baseStatistcsLogic,
            IQueryDatasLogic queryDatasLogic,
            TokenHelper tokenHelper)
        {
            _logger = logger;
            _queryDatasLogic = queryDatasLogic;
            _baseStatistcsLogic = baseStatistcsLogic;
            _tokenHelper = tokenHelper;
        }

        ///// <summary>
        ///// 查询操作员信息及其角色权限
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet]
        //public IActionResult StaffRoleMergeQuery()
        //{
        //    var result = new MergeQueryRepository().SelectLambdaUserInfo();
        //    return Ok(new { status = 1, result });
        //}

        /// <summary>
        /// 首页基本统计数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult BaseStatistics()
        {
            return Ok(Mock());
        }
        /// <summary>
        /// 首页基本数据查询mock
        /// </summary>
        /// <returns></returns>
        private object Mock()
        {
            try
            {
                //抄回/未抄回数据
                var backData = new
                {
                    copyBack = 261,
                    notCopyBack = 12
                };
                //水表状态信息
                var watermeterData = new
                {
                    linkFail = 7, //通讯异常
                    tapBad = 5, //阀门异常
                    underVoltage = 10, //欠压
                    notCopyBack = 12 //未抄回
                };

                //用水量
                var waterData = new object[12];
                for (var i = 0; i < waterData.Length; i++)
                {
                    waterData[i] = new
                    {
                        month = i + 1,
                        waterUsage = new Random(Simple.GetRandomSeed()).Next(10, 100)
                    };
                }
                return new
                {
                    errcode = 0,
                    msg = "ok",
                    data = new
                    {
                        backData,
                        watermeterData,
                        waterData
                    }
                };
            }
            catch (Exception e)
            {
                return new
                {
                    errcode = 1,
                    msg = e.Message
                };
            }
        }
        [HttpPost("/api/{X-Version}/Records/MetersRecord/Read")]
        public IActionResult SelectReadMeterRecord([FromBody] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息
            //获取配置
            //var areaId = token.payload.areaid;
            var pageSize = _baseStatistcsLogic.PageSize(token.payload.id);
            try
            {
                //获取所有查询条件
                var searchType = obj.searchType.ToString();
                var searchValue = obj.searchValue.ToString();
                var dataType = obj.dataType.ToString();
                var aid = obj.aid.ToString();
                var page = Simple.IntConvertString(obj.page.ToString(), 1);
                //时间--转换确认
                var dts = DateTime.TryParse(obj.startTime.ToString(), out DateTime startTime);
                var dte = DateTime.TryParse(obj.endTime.ToString(), out DateTime endTime);
                if (!dts || !dte)
                {
                    return Ok(new
                    {
                        errcode = 1,
                        msg = $"时间格式错误"
                    });
                }

                _queryDatasLogic.Token = token;
                _queryDatasLogic.DistrictId = aid;
                _queryDatasLogic.SearchType = searchType;
                _queryDatasLogic.SearchValue = searchValue;
           
                var result = _queryDatasLogic.SelectMeterDates(token, aid, searchType, searchValue, page, pageSize, dataType, startTime, endTime, out int count);
                //var result = new MeterDAL().SelectMeterData_where_date(token, searchType, searchValue, page, pageSize, dataType, startTime, endTime, out int count);
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok",
                    data = new
                    {
                        total = count,
                        pageSize,
                        list = result
                    }
                });
            }
            catch (Exception e)
            {
                 _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取水表读数数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        /// 未抄回表数据
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Records/MetersRecord/UnRead")]
        public IActionResult SelectUnReadMeterRecord([FromBody] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息
            //获取配置

            var pageSize = _baseStatistcsLogic.PageSize(token.payload.id);
            try
            {
                //获取所有查询条件
                var searchType = obj.searchType.ToString();
                var searchValue = obj.searchValue.ToString();
                var dataType = obj.dataType.ToString();
                var meterType = obj.meterType.ToString();
                var aid = obj.aid.ToString();
                var page = Simple.IntConvertString(obj.page.ToString(), 1);
                //时间--转换确认
                var dts = DateTime.TryParse(obj.readTime.ToString(), out DateTime readTime);
                if (!dts)
                {
                    return Ok(new
                    {
                        errcode = 1,
                        msg = $"时间格式错误"
                    });
                }
                _queryDatasLogic.Token = token;
                _queryDatasLogic.DistrictId = aid;
                _queryDatasLogic.SearchType = searchType;
                _queryDatasLogic.SearchValue = searchValue;
                var result = _queryDatasLogic.SelectNoDatesMeter(page, pageSize, dataType, meterType, readTime, out int count);
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok",
                    data = new
                    {
                        total = count,
                        pageSize,
                        list = result
                    }

                });
            }
            catch (Exception e)
            {
                 _logger.LogError(e.Message,e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取未抄回水表数据错误,错误:{e.Message}"
                });
            }
        }
        /// <summary>
        /// 查询平局用水量
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Records/MetersRecord/AvageDosage")]
        public IActionResult SelectWaterDosage([FromBody] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息
            //获取配置

            var pageSize = _baseStatistcsLogic.PageSize(token.payload.id);
            try
            {
                //获取所有查询条件
                var searchType = obj.searchType.ToString();
                var searchValue = obj.searchValue.ToString();
                var aid = obj.aid.ToString();
                var page = Simple.IntConvertString(obj.page.ToString(), 1);
                var statisticsType = Simple.IntConvertString(obj.statisticsType.ToString());
                var useageGreat = Simple.IntConvertString(obj.useageGreat.ToString());
                var useageLess = Simple.IntConvertString(obj.useageLess.ToString());
                //时间--转换确认
                var dts = DateTime.TryParse(obj.startTime.ToString(), out DateTime startTime);
                var dte = DateTime.TryParse(obj.endTime.ToString(), out DateTime endTime);
                if (!dts || !dte)
                {
                    return Ok(new
                    {
                        errcode = 1,
                        msg = $"时间格式错误"
                    });
                }
                _queryDatasLogic.Token = token;
                _queryDatasLogic.DistrictId = aid;
                //_queryDatasLogic.DistrictId = string.IsNullOrWhiteSpace(aid) ? Token.payload.areaid: aid;
                _queryDatasLogic.SearchType = searchType;
                _queryDatasLogic.SearchValue = searchValue;
                var result = _queryDatasLogic.SelectWaterDosage(page, pageSize, statisticsType, useageGreat, useageLess, startTime,
                    endTime, out int count);
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok",
                    data = new
                    {
                        total = count,
                        pageSize,
                        list = result
                    }
                });
            }
            catch (Exception e)
            {
                 _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取用水量数据错误,错误:{e.Message}"
                });
            }
        }
    }
}
